package com.njcb.game.util;

import com.njcb.ams.factory.comm.DataBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author LOONG
 */
public class SqlProviderUtils {
    /**
     * 根据sql模板和参数得到最终sql
     * @param sqlStr
     * @param inputMap
     * @return
     */
    public static String sqlProvider(String sqlStr, Map<String, String> inputMap) {
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.putAll(DataBus.getAttribute("paramMap", Map.class));
        paramsMap.putAll(inputMap);
        // 要替换一些字段的SQL（例子 select * from ${table} where ${filter}）
        List<Integer> head = new ArrayList();
        List<Integer> tail = new ArrayList();
        int headNum = 0;
        int tailNum = 0;
        List<String> allStr = new ArrayList();
        // 每个${ 与 } 的位置
        int headPos = sqlStr.indexOf("${");
        int tailPos = sqlStr.indexOf("}");
        while (headPos > -1) {
            if (headPos == headNum + 3) {
                head.set(head.size() - 1, headPos);
                tail.set(tail.size() - 1, tailNum);
            } else {
                head.add(headPos);
                tail.add(tailPos);
            }
            headNum = headPos;
            tailNum = tailPos;
            headPos = sqlStr.indexOf("${", headPos + 1);
            tailPos = sqlStr.indexOf("}", tailPos + 1);
        }
        for (int i = 0; i < head.size(); i++) {
            allStr.add(sqlStr.substring(head.get(i) + 2, tail.get(i)));
        }
        // 这里是针对上面保存的一些要替换的字段进行替换，具体怎么操作得详细理解代码
        for (int i = 0; i < allStr.size(); i++) {
            String paramName = allStr.get(i);
            if(!paramsMap.containsKey(paramName)){
                throw new RuntimeException("参数["+paramName+"]不存在");
            }
            sqlStr = sqlStr.replace("${" + paramName + "}", paramsMap.get(paramName));
        }
        return sqlStr;
    }

    public static void main(String[] args) {
        String sql = "select count(1)" +
                "  from game_register r" +
                " where r.token is not null" +
                "   and r.runners_no = ${runnersNo}";
        Map param = new HashMap();
        param.put("runnersNo","1006329");
        String rt = SqlProviderUtils.sqlProvider(sql,param);
        System.out.println(rt);
    }
}